var logger = require('pomelo-logger').getLogger(__filename);
var consts = require('../../../consts/consts');
var pomelo = require('pomelo');
var mem = pomelo.app.get('memclient');
var _ = require('underscore');

var exp = module.exports;

exp.enterRoom = function (playerInfo, sid, next) {
    playerInfo['sid'] = sid;
    var room = pomelo.app.room;
    room.enterRoom(playerInfo);

    setMem(playerInfo.uuid, room.serverId);

    next(null, {code: 200, roomInfo: room.baseInfo()});
};
exp.exitRoom = function (playerInfo, sid, next) {
    playerInfo.sid = sid;
    if (playerInfo.hasOwnProperty('player')) {
        playerInfo = playerInfo.player;
    }
    var room = pomelo.app.room;
    var value = room.exitRoom(playerInfo);
    if (value) {
        delMem(playerInfo.uuid);
    }
    next();
};
exp.enterDesk = function (msg, sid, next) {
    msg.player['sid'] = sid;
    var room = pomelo.app.room;
    //先判断你是否在桌子中
    var desk = room.findDeskByUuid(msg.player.uuid);
    if (!desk) {
        desk = room.findEmptyDesk();

        var result = desk.enterDesk(msg.player, msg.ready);
        if (result) {
            logger.trace('进入桌子成功');
            next(null, {code: consts.Code.Ok});
        } else {
            logger.warn('进入桌子失败,可能是因为你钱不够.');
            next(null, {code: consts.Player.Status.Desk_Money_No});
        }
    } else {
        logger.fatal('你已经在桌子中,开始游戏吧 ' + desk.name);
        var code = desk.ready(msg.player, msg.ready);
        next(null, {code: code});
    }
};
exp.removeDesk = function (msg, disPlayers, next) {
    var deskName = msg.deskName;
    var room = pomelo.app.room;
    var self = this;
    if (!!room) {
        room.deleteDesk(deskName);
        if (disPlayers && disPlayers.length > 0) {
            _.each(disPlayers, function (p) {
                if (p) {
                    self.exitRoom(p, null, function () {
                    });
                }
            });
        }
        next(null, {code: consts.Code.Ok});
    } else {
        next(null, {code: consts.Code.Fail});
    }
};
exp.backDesk = function (msg, sid, deskName, next) {
    var room = pomelo.app.room;
    if (!!room) {
        var info = room.backDesk(msg, deskName);
        next(null, {code: consts.Code.Ok, info: info, roomInfo: room.baseInfo()});
    } else {
        next(null, {code: consts.Code.Fail});
    }
};
exp.reConnect = function (msg, sid, deskName, next) {
    var room = pomelo.app.room;
    if (!!room) {
        room.reConnect(msg, deskName);
    }
    next();
};

var setMem = function (uuid, value) {
    value = {serverId: value};
    mem.set(uuid, value, function (err, data) {
        logger.info(data);
    });
};

var delMem = function (uuid) {
    mem.del(uuid, function (err, data) {
        logger.info('退出房间 删除mem ', data);
    });
};